//
//  ComposeViewController.swift
//  WeChat
//
//  Created by 梁迪 on 15/12/23.
//  Copyright © 2015年 梁迪. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    
    
    
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    //选择图片
    @objc private func selectPicture(){
        textView.resignFirstResponder()
        pictrueSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH / 3 * 2)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
            
        }
        
        
        
        
     
    }
    
    @objc private func selectEmoticonKeyboard(){
        
        print(__FUNCTION__)
        
    }
    
    @objc private func send(){
        var urlString = "2/statuses/update.json"
        guard let token = UserAccountViewModel().token else{
            
            SVProgressHUD.showInfoWithStatus("请重新登录", maskType: .Gradient)
            return
        }
        let parmeter = ["access_token":token,"status":textView.text ?? ""]
        
        
        if pictrueSelectorVC.imageList.count != 0 {
            
           // 非文本微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(pictrueSelectorVC.imageList.first!)
            
            NetworkTools.sharedTools.uploadImage(urlString, parameters: parmeter, imageData: imageData!, finished: { (dict, error) -> () in
            
                
                self.finishedUpdateStatus(dict, error: error)
            })
            
            
            
            
        }else{
            
            //文本微博
        
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parmeter) { (dict, error) -> () in
            
            
            self.finishedUpdateStatus(dict, error: error)
        }
        }
      
        
    }
    
    
    private func finishedUpdateStatus(dict:[String:AnyObject]?,error:NSError?){
        
        if error != nil{
            SVProgressHUD.showInfoWithStatus("发布微博失败,请检查网络", maskType: .Gradient)
            return
        }
        
        
        SVProgressHUD.showInfoWithStatus("发布微博成功", maskType: .Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)
        
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictrueSelectorVC.imageList.count == 0{
            
            textView.becomeFirstResponder()
        }
        
    }
    
    
    // 懒加载子视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        
        
        
//        tv.text = "请输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        
        return tv
    }()
    
    private lazy var pictrueSelectorVC:PictureSelectorCollectionViewController = PictureSelectorCollectionViewController()
    private lazy var placeHolderLabel: UILabel = UILabel(title: "请输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }

    }




extension ComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
   
}

extension ComposeViewController{
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setToolBar()
        registerNotification()
        setPictureSelectorVC()
        
    }
    
    private func setPictureSelectorVC(){
        addChildViewController(pictrueSelectorVC)
        view.addSubview(pictrueSelectorVC.view)
        view.bringSubviewToFront(toolBar)
        pictrueSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.bottom.equalTo(0)
        }
        
        
        
    }
    
    
    @objc private func keyboardWillChange(n:NSNotification){
        
        let duration = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offsetY = -screenH + endRect.origin.y
        print(offsetY)
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
            
        }
    }
    
    private func registerNotification(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        
        
        
    }
    
    
    
    private func setToolBar(){
        var items = [UIBarButtonItem]()
        
        //向数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        
        //遍历配置的数组
        for item in itemSettings {
            let imageName = item["imageName"]
            let itemBtn = UIButton(imageName:nil, backImageName: imageName!)
            if let action = item["actionName"]{
                itemBtn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
                
                
            }
            
            
            let barButtonItem = UIBarButtonItem(customView: itemBtn)
            
            items.append(barButtonItem)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
           
            
        }
        items.removeLast()
        
       toolBar.items = items
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)

        }
        
        
    }
    
    
    
    private func setTextView(){
        
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenH / 3)
            
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
  }
    
    
    
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel (title: "发微博", color:  UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }

    
}





